package lv.solcraft.replication.server.boot;

import java.util.Collection;

import lv.solcraft.replication.server.api.ServerFacade;
import lv.solcraft.replication.server.rest.ServerRestlets;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.Assert;

public class Server {

    private final ClassPathXmlApplicationContext applicationContext;
    private final ServerConfig serverConfig;
    private final ServerRestlets serverRestlets;

    public Server(ServerConfig serverConfig) throws Exception {
        this.serverConfig = serverConfig;
        serverConfig.validate();
        applicationContext = new ClassPathXmlApplicationContext(new String[] { "applicationContext-common.xml", "applicationContext-production.xml" });
        applicationContext.refresh();
        // set configuration
        ServerConfig configBean = (ServerConfig) applicationContext.getBean("serverConfig");
        configBean.copyFrom(serverConfig);
        // force to create beans (by default they have lazy-init)
        applicationContext.getBean("serverFacade");
        applicationContext.getBean("scheduler");
        this.serverRestlets = (ServerRestlets) applicationContext.getBean("serverRestlets");
    }

    public void stop() throws Exception {
        System.out.println("Stoppin server " + serverConfig.getServerName());
        if (applicationContext != null)
            applicationContext.close();
    }

    public ServerConfig getServerConfig() {
        return serverConfig;
    }

    public ServerFacade getFacade() {
        Collection<?> values = applicationContext.getBeansOfType(ServerFacade.class).values();
        Assert.notEmpty(values, "No serverFacade bean configured in application context");
        Assert.isTrue(values.size() == 1, "There are multip serverFacade bean configured in application context");
        return (ServerFacade) values.iterator().next();
    }

    public ServerRestlets getServerRestlets() {
        return serverRestlets;
    }
}
